var create_users = require('../../build/contracts/CreateUsers.json');
var Web3 = require('Web3')
var contract = require('truffle-contract')
var provider = new Web3.providers.WebsocketProvider("ws://127.0.0.1:8545");
var noteStore = contract(create_users);
noteStore.setProvider(provider);
//Mongoose setup to interact with the mongodb database
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var NotesModel = require('../../app/javascripts/Notes');
mongoose.connect("mongodb://localhost:27017/ChatOnBlackchain");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));



// Express server which the frontend with interact with
var express = require('express');
var app = express();
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.listen(3000, function() {
    console.log('Chat Ethereum server listening on port 3000!');
});

function setupNoteEventListner() {
    let NotesEvent;
    noteStore.deployed().then(function(i) {
        NotesEvent = i.NewNote({some:'args'},function (err,result) {
            if (err) {
                console.log(err)
                return;
            }
            console.log("result.args:" ,result.args)
            saveNote(result.args);
        });
    });

};

setupNoteEventListner();

function saveNote(n) {
    var count =0;
    console.log("n:",n[0])
    NotesModel.findOne({ 'blockchainId':count
    }, function (err, dbNotes) {
        if (dbNotes != null) {
            return;
        }
        var p = new NotesModel({address:n[0], note:n[1]});
        p.save(function (err) {
            if (err) {
                handleError(err);
            } else {
                NotesModel.count({}, function(err, count) {
                    count=count;
                    console.log("count is " + count);
                })
            }
        });
    });
};

//实时返回好友发来的信息
function getFriendNote(){
        let NotesEvent;
        noteStore.deployed().then(function(i) {
            NotesEvent = i.NewNote({some:'args'},function (err,result) {
                if (err) {
                    console.log(err)
                    return;
                }
                console.log("getFriendNote:" ,result.args)
            });
        });
};












